// orderDetails.js
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    reason: '',
    disabled: false,
    payColor: '#00a0e9',
    isTrue: true,
    appColor: app.appColor,
    getOrderCode: wx.getStorageSync('setOrderCode'),
    questionList: new Array,
    // 2020优惠活动
    // 提示弹出部分
    animationData: "",
    tabs: ["退票方式", "服务费", "儿童票"],
    activeIndex: 0,
    slideOffset: 0,
    tabW: 0,
    animationDetailed: "",
    topHeight: app.numHeight(),
    // 优惠券活动2020
    DId: '0',
    money: 0,
    // 优惠默认选中第一个
    select: 0,
    workData: "",
    discountsData: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      questionList: app.networkData.questionList ? app.networkData.questionList : ["如何取票乘车", "退票或改签", "出票失败问题", "技术服务费"]
    })
    app.showLoadings();
  },

  // 2020优惠券选择

  // 优惠活动2020 ===================================================
  noneD() {
    this.setData({
      select: -1,
      DId: 0,
      payMoney: Number(this.data.orderDetails.ShoudPayMent) - 0,
      money: 0
    })
  },
  discountsList: function (k) {
    let that = this;
    wx.request({
      url: app.serviceurl + 'Order/GetUserCoupon',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      dataType: 'json',
      success: function (res) {
        if (!res.data.Result) {
          return
        };
        let dataList = res.data.UserCoupons;
        // 查找获取用户下单时选择的优惠券，有过期的可能，解决：从res返回的数据中查找是否包含存储的ID，不存在则过期
        try {
          wx.getStorage({
            key: 'selectDId',
            success: function (res) {
              that.DId = res.data.DId;
              that.SelectMoney = Number(res.data.money);
              that.setData({
                DId: res.data.DId,
                SelectMoney: Number(res.data.money)
              })
            },
            fail: function (err) {
              that.DId = 0;
              that.SelectMoney = 0;
              // 存储用户选择的优惠券
              wx.setStorage({
                data: that.selectObj,
                key: 'selectDId',
              })
            }
          })
        } catch (err) {}
        that.setData({
          discountsData: dataList
        })
        // 测试数据
        // let dataList = that.data.discountsData;
        // 可用的优惠券列表
        let DList = new Array();
        // 不可用的优惠券数组
        // let minList = new Array();
        // dataList.forEach(item => {
        //   // 筛选可用优惠券
        //   if (item.IsCanUse && item.MinUseMoney <= k) {
        //     DList.push(item);
        //   } else {
        //     minList.push(item)
        //   }
        // })
        // // 对可用优惠券按优惠金额降序排序，默认选中第一个优惠券
        // var sortArr = [];
        // if (DList.length > 0) {
        //   sortArr = DList.sort(compare("CouponMoeny"));
        // };
        // that.setData({
        //   discountsData: sortArr.concat(minList),
        //   select: sortArr.length == 0 ? -1 : 0,
        //   money: sortArr.length == 0 ? 0 : sortArr[0].CouponMoeny,
        //   DId: sortArr.length == 0 ? 0 : sortArr[0].Id,
        //   payMoney: Number(that.data.orderinfo.ShouldPayment) - (sortArr.length == 0 ? 0 : Number(sortArr[0].CouponMoeny))
        // })
      },
      fail: function () {
        console.log("调用失败");
      },
      complete: function (res) {

      }
    })
  },
  DSelect(e) {
    let that = this;
    let t = this.data.orderDetails.TicketPayment;
    let minmoney = e.currentTarget.dataset.minmoney;
    let canuse = e.currentTarget.dataset.canuse;
    if (canuse == false) {
      return
    }
    // 订单金额未满
    if (t < minmoney) {
      return
    }
    this.setData({
      select: e.currentTarget.dataset.select,
      DId: e.currentTarget.dataset.id,
      payMoney: Number(this.data.orderDetails.ShouldPayment) - Number(e.currentTarget.dataset.money),
      money: e.currentTarget.dataset.money
    });
  },
  // 优惠活动2020   == END ===================================================

  // 底部提示弹出框
  tabClick: function (e) {
    var that = this;
    var idIndex = e.currentTarget.id;
    var offsetW = e.currentTarget.offsetLeft; //2种方法获取距离文档左边有多少距离
    this.setData({
      activeIndex: idIndex,
      slideOffset: offsetW
    });
  },
  bindChange: function (e) {
    var current = e.detail.current;
    var offsetW = current * this.data.tabW; //2种方法获取距离文档左边有多少距离
    this.setData({
      activeIndex: current,
      slideOffset: offsetW
    });
  },
  animationkNum: function (num) {
    //创建动画
    var animation = wx.createAnimation({
      // 动画执行时间
      duration: 250,
      timingFunction: "ease",
      // 延迟执行
      delay: 0,
    });
    animation.translate(0, num).step();
    this.setData({
      animationData: animation.export(),
    })
  },
  // 弹入/显示
  showFun: function (e) {
    if (e.currentTarget.dataset.hintindex > 3) {
      this.setData({
        discountShow: true,
      })
    } else {
      this.setData({
        animationShow: true,
        activeIndex: e.currentTarget.dataset.hintindex
      });
    }
    this.animationkNum(-80);
  },
  // 弹出/隐藏
  animtionHiden: function () {
    let that = this;
    this.animationkNum(850);
    setTimeout(function () {
      that.setData({
        animationShow: false,
        // 优惠券弹出框
        discountShow: false,
      });
    }, 200);
  },
  mask: function () {
    this.animtionHiden();
  },



  // =============================  END  =============================
  more: function () {
    wx.navigateTo({
      url: '/pages/problem/problem',
    })
  },
  // 请求订单详情数据
  message: function () {
    // this.data.getOrderCode是上一个历史订单，以便用户可以直接查看
    var orderCode = app.orderId ? app.orderId : this.data.getOrderCode;
    let getToken = app.accesstoken ? app.accesstoken : app.stanToken;
    this.invoiceCode = orderCode;
    var that = this;
    wx.request({
      url: app.serviceurl + 'Order/GetOrderDetail',
      header: {
        Authorization: "Bearer " + getToken
      },
      data: {
        OrderCode: orderCode
      },
      dataType: 'json',
      success: function (res) {
        if (!res.data.Result) {
          that.setData({
            ref: res.data,
          });
          return
        };
        if (typeof (res.data.TakeManList) != 'undefined' && res.data.TakeManList != null) {
          res.data.TakeManList.forEach(function (item) {
            item.TakeManPhone = item.TakeManPhone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
            item.TakeManCardId = item.TakeManCardId.replace(/(\d{6})\d{4}(\d{4})/, '$1****$2');
          })
        }
        if (res.data.FeeInfo) {
          res.data.FeeInfo.statusTxt = that.feeState(res.data.FeeInfo.status);
        }
        // that.SelectMoney = 0;
        if (res.data.OrderMain.couponMoney != 0) {
          var newMoney = 0;
        } else {
          var newMoney = that.SelectMoney;
        }
        that.setData({
          orderDetails: res.data.OrderMain,
          OrderStatus: res.data.OrderStatus,
          password: res.data.IsShowTicketPassword ? res.data.TicketPassword : '',
          rider: res.data.TakeManList,
          code: res.data.OrderMain.Sn,
          message: res.data.OrderMain,
          ref: res.data,
          HandsetNumber: app.HandsetNumber,
          reason: res.data.CannotRefundReason,
          week: "星期" + "日一二三四五六".charAt(new Date(res.data.OrderMain.StartDate).getDay()),
          moneyDis: Number(res.data.OrderMain.ShoudPayMent) - (newMoney ? newMoney : 0)
        });
        app.hideLoadings();
      },
      fail: function (error) {
        app.hideLoadings();
      },
      complete: function () {
        app.hideLoadings();
      }
    })

  },
  // 判断发票状态
  feeState: function (b) {
    if (b == -1) {
      return "申请开发票"
    } else if (b == 0) {
      return "已申请"
    } else if (b == 1) {
      return "已开票"
    } else if (b == 2) {
      return "已撤销"
    } else if (b == 3) {
      return "已开取"
    }
  },
  // 温馨提示
  Doubt: function (e) {
    let index = e.currentTarget.dataset.index;
    // let title;
    // if (index == 0) {
    //   title = "如何取票";
    // } else if (index == 1) {
    //   title = "退票或改签";
    // } else if (index == 2) {
    //   title = "支付成功，出票失败";
    // } else if (index == 3) {
    //   title = "线路相同，票价不同";
    // }
    wx.navigateTo({
      url: '/pages/problem/problem?index=' + index,
    })
  },
  // 提示框定时器
  hintTime: function (that) {
    let num = 2;
    const time = setInterval(function () {
      if (num <= 0) {
        that.setData({
          hint: false
        });
        return;
      }
      num--;
    }, 1000)
  },

  // 取消订单
  abandon: function () {
    let that = this;
    let orderCode = app.orderId ? app.orderId : this.data.getOrderCode;
    wx.showModal({
      title: '确认取消',
      content: '确定取消该订单吗？',
      confirmText: "确定",
      cancelText: "放弃",
      success: function (res) {
        if (res.confirm) {
          that.setData({
            isTrue: false
          })
          app.showLoadings();
          app.busHint = false;
          wx.request({
            url: app.serviceurl + 'Order/CancleOrder',
            header: {
              Authorization: "Bearer " + app.accesstoken
            },
            data: {
              OrderCode: orderCode
            },
            dataType: 'json',
            success: function (res) {
              if (!res.data.Result) {
                wx.showModal({
                  title: "取消订单失败",
                  content: res.data.Message,
                  showCancel: false,
                  confirmText: "确定",
                  success: function (res) {}
                })
                return
              }
              app.busHintRepetition = false;
              that.message();
              wx.setStorage({
                data: that.selectObj,
                key: 'selectDId',
              })
              that.setData({
                isTrue: false
              })
            },

            fail: function (err) {
              wx.showModal({
                title: "取消订单失败",
                content: res.data.Message,
                showCancel: false,
                confirmText: "确定",
                success: function (res) {}
              })
              that.setData({
                isTrue: true
              });
              app.hideLoadings();
            },

            complete: function (res) {
              app.hideLoadings();
              that.setData({
                hintMessage: res.data.Message,
                hint: true
              })
              that.hintTime(that);
            }
          });
        }
      }
    });
  },

  anewVote: function () {
    wx.redirectTo({
      url: '/pages/buslines/buslines'
    })
  },
  // 服务费发票开取
  invoice: function () {
    // let status = this.data.ref.FeeInfo.statusTxt;
    let status = this.data.ref.FeeInfo.status;
    if (status == -1) {
      wx.navigateTo({
        url: '/pages/personcenter/personcenter?code=' + this.invoiceCode
      })
    }

  },


  openToast: function () {
    wx.showToast({
      title: '支付成功',
      icon: 'success',
      duration: 800
    });
  },
  pay: function (e) {
    this.setData({
      disabled: true,
      payColor: '#1BB166'
    });

    var that = this;

    wx.request({
      url: app.serviceurl + 'Order/PayOrder',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: {
        orderSn: app.orderId,
        couponId: that.DId ? that.DId : 0
      },
      success: function (res) {
        if (res.data.Result) {
          if (!res.data.IsNoPay) {
            wx.requestPayment({
              timeStamp: res.data.timeStamp,
              nonceStr: res.data.nonceStr,
              package: res.data.package,
              signType: res.data.signType,
              paySign: res.data.paySign,
              success: function (resr) {
                if (resr.errMsg == "requestPayment:ok") {
                  //支付成功
                  wx.redirectTo({
                    url: '/pages/applySuccess/applySuccess',
                  })
                  that.openToast();
                  that.message();
                  // app.orderState = '已付款';
                }
              }
            })
          } else {
            wx.setStorage({
              data: that.selectObj,
              key: 'selectDId',
            })
            app.showLoadings();
            wx.showToast({
              title: '支付成功',
              icon: 'succes',
              duration: 800,
              mask: true
            })
            that.message();
          }
        } else {
          wx.showToast({
            title: res.data.Message,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function (error) {
        console.log(error);
      },
      complete: function (res) {
        app.hideLoadings();
        if (res) {
          var time = setTimeout(function () {
            that.setData({
              disabled: false,
              payColor: '#22cc77'
            });
          }, 1000)
        }

      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.message();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  backto: function () {
    wx.switchTab({
      url: '../../index/index',
    })
  },
  openConfirm: function () {
    if (this.data.ref.IsCanRefund == true && this.data.ref.IsShowCannotRefund == false) {
      wx.navigateTo({
        url: '../../refund/refund?code=' + this.data.code,
      })
    } else {
      this.refundreson();
    }

  },
  refundreson: function () {
    wx.showModal({
      content: this.data.reason,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {}
      }
    });
  },
  refundRule: function () {
    wx.showModal({
      title: '退票规则',
      content: '*退款手续费不含保险金额（为实际付款金额减去保险金额）。\r\n1、距离开车时间2小时前办理退票，按票面额10%计收退票费。\r\n2、距离开车时间2小时以内办理退票，按票面额20%计收退票费。\r\n3、班车开车后1小时内办理退票，按票面额50%计收退票费。 \r\n4、班车开车1小时后不办理退票。\r\n5、确认退款后，退款金额将于7个工作日内退回。 \r\n6、实际退款时间以服务器执行时间为准。\r\n注：实际运行中，有可能出现不同车站不同费率的情况，以车站实际退款为准（各车站的退票规则并不完全一致）。',
      showCancel: false,
      success(res) {

      }
    })
  },
  phoneservice: function (e) {
    wx.makePhoneCall({
      phoneNumber: "96606"
    });
  },
})